/*
 * @lc app=leetcode.cn id=112 lang=typescript
 *
 * [112] 路径总和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */
function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
    if (!root) {
        return false;
    }
    return loop(root, targetSum - root.val, targetSum - root.val);
};

function loop(root: TreeNode | null, count: number, target: number): boolean {
    if (!root) {
        return false;
    }
    if (!root.left && !root.right) {
        if (count === 0) {
            return true;
        } else {
            return false;
        }
    }

    if (root.left) {
        count -= root.left.val;
        if (loop(root.left, count, target)) return true
        count += root.left.val;
    }

    if (root.right) {
        count -= root.right.val;
        if (loop(root.right, count, target)) return true
        count += root.right.val;
    }
    return false;
}
// @lc code=end

